<%@ page errorPage="error.jsp" %>
<%@ page import="BusinessLogic.ControllerFacade" %>
<%@ page import= "org.jfree.chart.ChartFactory" %>
<%@ page import= "org.jfree.chart.ChartFrame" %>
<%@ page import= "org.jfree.chart.JFreeChart" %>
<%@ page import= "org.jfree.data.general.DefaultPieDataset" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="com.sun.image.codec.jpeg.*"%>
<%@ page import="java.util.*"%>
<%@ page import= "org.jfree.chart.ChartPanel" %>
<%@ page import= "org.jfree.chart.plot.PiePlot" %>
<%@ page import= "org.jfree.data.general.PieDataset" %>
<%@ page import= "java.text.NumberFormat" %>
<%@ page import= "org.jfree.chart.labels.StandardPieSectionLabelGenerator" %>


<%
    ControllerFacade c = (ControllerFacade) session.getAttribute("c");
    String sort  = request.getParameter("sort");
    String count = request.getParameter("count");
	String type;
	boolean highestRate = false;
	
	if(sort.equals("most"))
	{
		type = "highest";
		highestRate = true;
	}
	else
	{
		type = "lowest";
		highestRate = false;
	}	

    HashMap<String, Integer> ans = (HashMap<String, Integer>) c.getMovieRates(highestRate, Integer.parseInt(count));
    Set set = ans.keySet();
    DefaultPieDataset dataset = new DefaultPieDataset();
	for (Iterator iterator = set.iterator(); iterator.hasNext();) {
				String name = (String) iterator.next();
				dataset.setValue(name, (ans.get(name)));
	}
    
	JFreeChart chart = ChartFactory.createPieChart(
            "Pie Chart for " + type + " rated movies ",  // chart title
            dataset,             // data
            true,               // include legend
            true,
            false
        );
        
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setNoDataMessage("No data available");
    plot.setCircular(false);
    plot.setLabelGap(0.02);
     

    BufferedImage image = chart.createBufferedImage(600, 400);

    ServletOutputStream out1 = response.getOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out1);
    encoder.encode(image);
 %>
